<?php

namespace app\common\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Account extends Model
{

    protected $name = 'member_account';

    protected $resultSetType = 'collection';

    public static function getAll($request, $type = 1, $is_bonus = false)
    {
        try {
            $param = $request->param();
            $map['is_del'] = 0;
            $map['intro'] = ['neq','赠送积分'];
            if (isset($param['category']) && $param['category']) {
                $map['category'] = $param['category'];
            }
            if (isset($param['type']) && $param['type']) {
                $map['type'] = $param['type'];
            }
            if ($is_bonus) {
                $map['is_bonus'] = 1;
            }
            $that = parent::with(['user', 'user2'])->where($map);
            if ($param['keyword']) {
                $ids = Member::whereLike('code|nickname|mobile', '%' . $param['keyword'] . '%')->column('id');
                $that->whereIn('uid', $ids);
            }
            if ($param['keyword2']) {
                $ids = Member::whereLike('code|nickname|mobile', '%' . $param['keyword2'] . '%')->column('id');
                $that->whereIn('source', $ids);
            }

            if ($param['times']) {
                $value = explode(' - ', $param['times']);
                $that->whereBetween('create_time', [strtotime($value[0]), strtotime($value[1])]);
            }
            if ($type == 1) {
                return $that->order('create_time', 'desc')
                    ->paginate(cache('system')['list_rows'], false, ['query' => $request->get()]);
            } else {
                return $that->order('create_time', 'desc')->select()->toArray();
            }

        } catch (\Exception $e) {
            return [];
        }
    }

    public function user()
    {
        return $this->hasOne('Member', 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function user2()
    {
        return $this->hasOne('Member', 'id', 'source')->field('id,code,nickname,mobile');
    }

    public static function getList($uid, $page, $type, $category = '', $all = '')
    {
        try {
            $map['uid'] = $uid;
            $map['type'] = $type;
            if ($all == 1) {
                return parent::with(['user' => function ($query) {
                    $query->field('id,code');
                }])->where($map)
                    ->where('type', $type)
                    ->order('create_time', 'desc')
                    ->page(intval($page), 10)->field('intro,create_time,create_date,fx,amount,balance,source')->select();
            } else if ($all == 2) {
                return parent::where($map)
                    ->where('category', 'in', '6,9')
                    ->order('create_time', 'desc')
                    ->page(intval($page), 10)->field('uid,intro,type,create_time,create_date,fx,amount,balance,source')->select();
            } else {
                if ($category) $map['category'] = $category;
                return parent::with(['user' => function ($query) {
                    $query->field('id,code');
                }])->where($map)->order('create_time', 'desc')
                    ->page(intval($page), 10)->field('intro,create_time,create_date,fx,amount,balance,source')->select();
            }


        } catch (\Exception $e) {
            return [];
        }
    }

    public static function adds($id, $type, $amount, $intro, $fx, $source = 0, $category = 0, $is_grant = 2,$is_bonus = 0,$insert = true)
    {
        try {
            $data = [
                'uid' => $id,
                'type' => $type,
                'intro' => $intro,
                'amount' => $amount,
                'balance' => User::where('id',$id)->value($type),
                'fx' => $fx,
                'create_time' => time(),
                'create_date' => date('Y-m-d'),
                'source' => $source,
                'category' => $category,
                'is_grant' => $is_grant,
                'is_bonus' => $is_bonus
            ];
            if ($insert) {
                parent::create($data);
                return true;
            } else {
                return $data;
            }

        } catch (\Exception $e) {

            return $e->getMessage();
        }
    }
    public static function add($id, $type, $amount, $intro, $fx, $source = 0, $category = 0,$msg='')
    {
        try {
            parent::create([
                'uid' => $id,
                'type' => $type,
                'intro' => $intro,
                'amount' => $amount,
                'balance' => db('user')->where('id',$id)->value($type),
                'fx' => $fx,
                'create_time' => time(),
                'create_date' => date('Y-m-d'),
                'source' => $source,
                'category' => $category,
                'msg' => $msg,
                // 'is_bonus' => $is_bonus
            ]);
            if ($fx == '+') {
                db('user')->where('id', $id)->setInc($type, $amount);
                if(in_array($intro,['团长奖励','直推奖'])){
                    db('user')->where('id', $id)->setInc('bonus_sum', $amount);
                }
            } else {
                db('user')->where('id', $id)->setDec($type, $amount);
            }
            if($intro=='团长奖励'){
                db('user')->where('id', $id)->setInc('head');
            }
            return true;

        } catch (\Exception $e) {
            // dump($e);
            return $e->getMessage();
        }
    }

    public static function rotation($param, $user, $system)
    {
        try {
            if ($system[$param['type'] . '_tf_open'] != 1) {
                return json(['code' => -1, 'msg' => '暂不可互转']);
            }

            $param['code'] = trim($param['code']);
            $is = User::where('code', $param['code'])->field('id,code,is_service')->find();
            if (empty($is)) {
                return json(['code' => -1, 'msg' => '收款账户不存在']);
            }

//            $count = Relation::where(['uid' => $user['id'], 'new_uid' => $is['id']])->count('id');
//            if ($count <= 0) {
//                return json(['code' => -1, 'msg' => '收款人不属于您的下级无法转账']);
//            }
            if ($param['money'] < $system[$param['type'] . '_tf_min']) {
                return json(['code' => -1, 'msg' => '最低互转:' . $system[$param['type'] . '_tf_min']]);
            }
            if ($system[$param['type'] . '_tf_bs'] && $system[$param['type'] . '_tf_bs'] > 0) {
                if ($param['money'] % $system[$param['type'] . '_tf_bs'] != 0) {
                    return json(['code' => -1, 'msg' => '互转倍数:' . $system[$param['type'] . '_tf_bs']]);
                }
            }

            if ($user[$param['type']] < $param['money']) {
                return json(['code' => -1, 'msg' => '余额不足']);
            }
            $cost = $param['money'] * $system[$param['type'] . '_tf_cost'];

            $money = $param['money'] - $cost;

            if (md5($param['pay_password']) != $user['pay_password']) {
                return json(['code' => -1, 'msg' => '支付密码错误']);
            }
            self::add($user['id'], $user['code'], $param['type'], '转出', $money, '-', $is['id'], 25);
            if ($cost > 0) {
                self::add($user['id'], $user['code'], $param['type'], '转出手续费', $cost, '-', $is['id'], 25);
            }
            self::add($is['id'], $is['code'], $param['type'], '转入', $money, '+', $user['id'], 25);

            return json(['code' => 1, 'msg' => '已转出']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }


    /**
     * 原点 2020年9月4日11:34:54 新增后事件处理
     *
     * @param Model $user
     */
    public static function onAfterInsert($user)
    {

    }
    public function get_account($type, $page, $uid)
    {
        try {
        	$where = ['uid'=>$uid];
            
        	if($type=='yeji'){
        		$where['intro'] = ['in',['直推奖','团长奖励']];
			}else{
				$where['type'] = $type;
			}
            return $this->where($where)
                // ->where('category','<',20)
                ->page($page, 10)
                ->order('create_time desc')->select();
        } catch (\Exception $e) {
            return [];
        }
    }

}
